package com.kcnet.qk.util;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.kcnet.qk.app.AppContext;
import com.kcnet.qk.constant.Const;
import com.kcnet.qk.controller.addfriend.AddFriendAdoptCTR;
import com.kcnet.qk.controller.addfriend.AddFriendFriendCTR;
import com.kcnet.qk.controller.addfriend.AddFriendHomeCTR;
import com.kcnet.qk.controller.addfriend.AddFriendPhoneCTR;
import com.kcnet.qk.controller.addfriend.AddFriendRecommedCTR;
import com.kcnet.qk.controller.addfriend.AddSearchPhoneCTR;
import com.kcnet.qk.controller.dynamic.TemeLineSendAllFriendMsgCTR;
import com.kcnet.qk.controller.dynamic.TemeLineSendHomeCTR;
import com.kcnet.qk.controller.dynamic.TemeLineSendHomeTimeCTR;
import com.kcnet.qk.controller.dynamic.TimeLineSendImgAndTextCTR;
import com.kcnet.qk.controller.dynamic.TimeLineSendImgCTR;
import com.kcnet.qk.controller.dynamic.TimeLineSendTextCTR;
import com.kcnet.qk.controller.group.TeamAttsTeamCTR;
import com.kcnet.qk.controller.group.TeamFriendZanHomeCTR;
import com.kcnet.qk.controller.group.TeamRqFriendCTR;
import com.kcnet.qk.controller.group.TeamTeamMagCTR;
import com.kcnet.qk.controller.hdyh.HdFriendTimeLineZans;
import com.kcnet.qk.controller.hdyh.HdTimeLineZans;
import com.kcnet.qk.controller.hdyh.HdyhNotiyCTR;
import com.kcnet.qk.model.AddSearchData;
import com.kcnet.qk.model.BaseData;
import com.kcnet.qk.model.HdyhFriendData;
import com.kcnet.qk.model.MsgData;
import com.kcnet.qk.model.PhoneData;
import com.kcnet.qk.model.TeamData;
import com.kcnet.qk.model.TimeLineSendData;
import com.kcnet.qk.model.TimeLineSendHomeData;
import com.kcnet.qk.netty.NettyClient;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.jesse.nativelogger.NLogger;


/**
 * Created by Administrator on 2018/5/10 0010.
 */

public class JsonNettyData {
    private static String TAG = "JsonNettyData";

    /**
     * 清空系统通信录数据
     */
    public static void clearContact() {
        ContentResolver cr = AppContext.getInstance().getContext().getContentResolver();
        // 查询contacts表的所有记录
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);
        // 如果记录不为空
        if (cursor.getCount() > 0) {
            // 游标初始指向查询结果的第一条记录的上方，执行moveToNext函数会判断
            // 下一条记录是否存在，如果存在，指向下一条记录。否则，返回false。
            while (cursor.moveToNext()) {
                //  String rawContactId = "";
                // 从Contacts表当中取得ContactId
//                  String id = cursor.getString(cursor
//                          .getColumnIndex(ContactsContract.Contacts._ID));

                String name = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


                //根据姓名求id
                Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");

                Cursor cursor1 = cr.query(uri, new String[]{ContactsContract.Contacts.Data._ID}, "display_name=?", new String[]{name}, null);
                if (cursor1.moveToFirst()) {
                    int id = cursor1.getInt(0);
                    //根据id删除data中的相应数据
                    cr.delete(uri, "display_name=?", new String[]{name});
                    uri = Uri.parse("content://com.android.contacts/data");
                    cr.delete(uri, "raw_contact_id=?", new String[]{id + ""});
                }
            }
        }
    }
//    final MediaScannerConnection msc = new MediaScannerConnection(mContext, new MediaScannerConnection.MediaScannerConnectionClient() {
//        public void onMediaScannerConnected() {
//            msc.scanFile("/sdcard/Boohee/image.jpg", "image/jpeg");
//        }
//        public void onScanCompleted(String path, Uri uri) {
//            Log.v(TAG, "scan completed");
//            msc.disconnect();
//        }
//    });

    /**
     * 批量添加通讯录
     *
     * @throws
     * @throws
     */
    public static void batchAddContact(List<PhoneData.PhoneItem> list)
            throws OperationApplicationException, RemoteException {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        int rawContactInsertIndex = 0;
        for (PhoneData.PhoneItem contact : list) {
            rawContactInsertIndex = ops.size(); // 有了它才能给真正的实现批量添加

            ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                    .withYieldAllowed(true).build());

            // 添加姓名
            ops.add(ContentProviderOperation
                    .newInsert(
                            android.provider.ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
                            rawContactInsertIndex)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contact.getName())
                    .withYieldAllowed(true).build());
            // 添加号码
            ops.add(ContentProviderOperation
                    .newInsert(
                            android.provider.ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
                            rawContactInsertIndex)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.getPhone())
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, "").withYieldAllowed(true).build());
        }
        if (ops != null) {
            // 真正添加
            ContentProviderResult[] results = AppContext.getInstance().getContext().getContentResolver()
                    .applyBatch(ContactsContract.AUTHORITY, ops);
            // for (ContentProviderResult result : results) {
            // GlobalConstants
            // .PrintLog_D("[GlobalVariables->]BatchAddContact "
            // + result.uri.toString());
            // }
        }
    }

    public static void sendToServerFlag(long id, int status, String msg) {

        String body = "{\"code\":2,\"msg\":\"" + msg + "\",\"id\":" + id + ",\"status\":" + status + "}";
        NLogger.d(TAG, "发送数据:" + body);
        NettyClient.getInstance().sendMsgToServer(body.getBytes());
    }

    public static void pasrsJson(String value) {
        try {
            if (AppContext.taskId > -1) {
                JsonNettyData.sendToServerFlag(AppContext.taskId, 3, "执行失败,收到新任务强制终止");
            }
            JSONObject jb = new JSONObject(value);
            AppContext.taskId = jb.getLong("id");
            AppContext.taskStartTime = System.currentTimeMillis();
            if (jb.getInt("code") == 1) {
                PhoneData data = JSON.parseObject(value, PhoneData.class);
                NLogger.d("HTML", "开始执行任务");
                sendToServerFlag(AppContext.taskId, 1, "开始执行");
                //操作插入电话号码
                if (data.getData().getIsClaer() == 1) {
                    clearContact();
                }
                batchAddContact(data.getData().getList());
                sendToServerFlag(AppContext.taskId, 2, "执行完成");
                AppContext.taskId = -1;
                NLogger.d(TAG, "存储更新通讯录执行完成");
                ToastUtil.showToast(AppContext.getInstance().getContext(), "执行完成");
            } else if (jb.getInt("code") == 17) {
                //发送信息给所有好友
                MsgData data = JSON.parseObject(value, MsgData.class);
                TemeLineSendAllFriendMsgCTR.getInstance().setParms(data.getData().getCanClickCount(), data.getData().getMinWait(), data.getData().getMaxWait(), data.getData().getContent());
                EventBus.getDefault().post(new Integer(Const.KEY_ADD_FIREND_PHONE));
                NLogger.d(TAG, "开始执行 MSGG发布消息任务");
                AppContext.taskType = Const.KEY_ADD_FIREND_PHONE;
                sendToServerFlag(AppContext.taskId, 1, "开始执行");
                if (!AppUtil.checkPermission(AppContext.getInstance().getContext())) {
                    AppUtil.jumpSetting(AppContext.getInstance().getContext());
                } else {

                    AppUtil.jumpToMsg(AppContext.getInstance().getContext());
                }
            } else {
                int addType = -1;
                BaseData data;
                switch (jb.getInt("code")) {
                    case 1:
                        //下发好友通讯轮
                        break;
                    case 2://添加通讯录好友
                        data = JSON.parseObject(value, BaseData.class);
                        AddFriendPhoneCTR.getInstance().setParms(data.getData().getCanClickCount(), data.getData().getMinWait(), data.getData().getMaxWait());
                        addType = Const.KEY_ADD_FIREND_PHONE;
                        NLogger.d(TAG, "开始执行任务  添加通讯录好友");
                        break;
                    case 3://添加好友的好友
                        data = JSON.parseObject(value, BaseData.class);
                        AddFriendFriendCTR.getInstance().setParms(data.getData().getCanClickCount(), data.getData().getMinWait(), data.getData().getMaxWait());
                        addType = Const.KEY_ADD_FIREND_FRIED;
                        NLogger.d(TAG, "开始执行任务 添加好友的好友");
                        break;
                    case 4://添加推荐好友
                        data = JSON.parseObject(value, BaseData.class);
                        AddFriendRecommedCTR.getInstance().setParms(data.getData().getCanClickCount(), data.getData().getMinWait(), data.getData().getMaxWait());
                        addType = Const.KEY_ADD_FIREND_RECOMMED;
                        NLogger.d(TAG, "开始执行任务 添加推荐好友");
                        break;
                    case 5://通过好友请求
                        data = JSON.parseObject(value, BaseData.class);
                        AddFriendAdoptCTR.getInstance().setParms(data.getData().getCanClickCount(), data.getData().getMinWait(), data.getData().getMaxWait());
                        addType = Const.KEY_ADD_FIREND_ADOPT;
                        NLogger.d(TAG, "开始执行任务 通过好友请求");
                        break;
                    case 6://添加主页好友
                        data = JSON.parseObject(value, BaseData.class);
                        AddFriendHomeCTR.getInstance().setParms(data.getData().getCanClickCount(), data.getData().getMinWait(), data.getData().getMaxWait());
                        addType = Const.KEY_ADD_FIREND_HOME;
                        NLogger.d(TAG, "开始执行任务 添加主页好友");
                        break;
                    case 7://添加搜索名称好友
                        AddSearchData addSearchData = JSON.parseObject(value, AddSearchData.class);
                        AddSearchPhoneCTR.getInstance().setParms(addSearchData.getData().getCanClickCount(), addSearchData.getData().getMinWait(),
                                addSearchData.getData().getMaxWait(), addSearchData.getData().getCity(), addSearchData.getData().getList());
                        addType = Const.KEY_ADD_FRIEND_SEATCH_NAME;
                        NLogger.d(TAG, "开始执行任务 添加搜索名称好友");
                        break;
                    case 8://添加搜索邮箱好友
                        AddSearchData addSearchData2 = JSON.parseObject(value, AddSearchData.class);
                        AddSearchPhoneCTR.getInstance().setParms(addSearchData2.getData().getCanClickCount(), addSearchData2.getData().getMinWait(), addSearchData2.getData().getMaxWait()
                                , addSearchData2.getData().getCity(), addSearchData2.getData().getList());
                        addType = Const.KEY_ADD_FRIEND_SEATCH_EMAIL;
                        NLogger.d(TAG, "开始执行任务 添加搜索邮箱好友");
                        break;
                    case 9://主页点赞
                        data = JSON.parseObject(value, BaseData.class);
                        HdTimeLineZans.getInstance().setParms(data.getData().getCanClickCount(), data.getData().getMinWait(), data.getData().getMaxWait());
                        addType = Const.KEY_HDYH_TIMELINE;
                        NLogger.d(TAG, "开始执行任务 主页点赞");
                        break;
                    case 10://主页好友点赞
                        HdyhFriendData hdyhFriendData = JSON.parseObject(value, HdyhFriendData.class);
                        HdFriendTimeLineZans.getInstance().setParms(hdyhFriendData.getData().getCanClickCount(),
                                hdyhFriendData.getData().getMinWait(), hdyhFriendData.getData().getMaxWait(), hdyhFriendData.getData().getFriendsCount());
                        addType = Const.KEY_HDYH_TIMELINE_FRIEND;

                        NLogger.d(TAG, "开始执行任务 主页好友点赞");
                        break;
                    case 11://养号
                        data = JSON.parseObject(value, BaseData.class);
                        HdyhNotiyCTR.getInstance().setParms(data.getData().getCanClickCount(), data.getData().getMinWait(), data.getData().getMaxWait());
                        addType = Const.KEY_HDYH_yh;

                        NLogger.d(TAG, "开始执行任务 养号");
                        break;
                    case 12://发布文字动态
                        TimeLineSendData timeLineSendData = JSON.parseObject(value, TimeLineSendData.class);
                        TimeLineSendTextCTR.getInstance().setParms(timeLineSendData.getData().getContent());
                        addType = Const.KEY_TIMELINE_SEND_TEXT;

                        NLogger.d(TAG, "开始执行任务 发布文字动态");
                        break;
                    case 13://发布图片动态
                        TimeLineSendData timeLineSendData1 = JSON.parseObject(value, TimeLineSendData.class);
                        Collections.reverse(timeLineSendData1.getData().getImg());
                        TimeLineSendImgCTR.getInstance().setParms(timeLineSendData1.getData().getImg());
                        addType = Const.KEY_TIMELINE_SEND_IMG;
                        for (String name : timeLineSendData1.getData().getImg()) {
                            String path = FileUtils.getPicutures() + name;
                            Log.d("HTML", "图片路径:" + path);
                            AppContext.getInstance().getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(path))));
                        }
                        NLogger.d(TAG, "开始执行任务 发布图片动态");
                        break;
                    case 14://发布图文动态
                        TimeLineSendData timeLineSendData2 = JSON.parseObject(value, TimeLineSendData.class);
                        Collections.reverse(timeLineSendData2.getData().getImg());
                        for (String name : timeLineSendData2.getData().getImg()) {
                            String path = FileUtils.getPicutures() + name;
                            Log.d("HTML", "图片路径:" + path);
                            AppContext.getInstance().getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(path))));
                        }
                        TimeLineSendImgAndTextCTR.getInstance().setParms(timeLineSendData2.getData().getContent(), timeLineSendData2.getData().getImg());
                        addType = Const.KEY_TIMELINE_SEND_IMG_TEXT;

                        NLogger.d(TAG, "开始执行任务 发布图文动态");
                        break;
                    case 15://发送好友主页
                        TimeLineSendHomeData timeLineSendHomeData = JSON.parseObject(value, TimeLineSendHomeData.class);
                        TemeLineSendHomeCTR.getInstance().setParms(timeLineSendHomeData.getData().getMinWait(), timeLineSendHomeData.getData().getMaxWait(),
                                timeLineSendHomeData.getData().getContent(), timeLineSendHomeData.getData().getRunType());
                        addType = Const.KEY_TIMELINE_SEND_HOME;
                        NLogger.d(TAG, "开始执行任务 发送好友主页");
                        break;
                    case 16://发送主页到好友时间线
                        TimeLineSendHomeData timeLineSendHomeData2 = JSON.parseObject(value, TimeLineSendHomeData.class);
                        TemeLineSendHomeTimeCTR.getInstance().setParms(timeLineSendHomeData2.getData().getMinWait(), timeLineSendHomeData2.getData().getMaxWait(),
                                timeLineSendHomeData2.getData().getContent());
                        addType = Const.KEY_TIMELINE_SEND_HOME_TIME;
                        NLogger.d(TAG, "开始执行任务 发送主页到好友时间线");
                        break;
                    case 17:

                        //注释没做
                        break;
                    case 18://小组管理
                        TeamData teamData1 = JSON.parseObject(value, TeamData.class);
                        TeamTeamMagCTR.getInstance().setParms(teamData1.getData().getCanClickCount(), teamData1.getData().getMinWait(),
                                teamData1.getData().getMaxWait(), teamData1.getData().getContent(), teamData1.getData().getRunType());
                        addType = Const.KEY_TEAM_TEAM_MAG;
                        NLogger.d(TAG, "开始执行任务 小组管理");
                        break;
                    case 19://关注主页
                        TeamData teamData2 = JSON.parseObject(value, TeamData.class);
                        TeamAttsTeamCTR.getInstance().setParms(teamData2.getData().getCanClickCount(), teamData2.getData().getMinWait(),
                                teamData2.getData().getMaxWait(), teamData2.getData().getContent());
                        addType = Const.KEY_TEAM_ATTS_TEAM;
                        NLogger.d(TAG, "开始执行任务 关注主页");
                        break;
                    case 20://邀请好友进小组
                        TeamData teamData3 = JSON.parseObject(value, TeamData.class);
                        TeamRqFriendCTR.getInstance().setParms(teamData3.getData().getCanClickCount(), teamData3.getData().getMinWait(),
                                teamData3.getData().getMaxWait(), teamData3.getData().getContent());
                        addType = Const.KEY_TEAM_RQ_FRIEND_TEAM;
                        NLogger.d(TAG, "开始执行任务 邀请好友进小组");
                        break;
                    case 21://邀请好友点赞主页
                        TeamData teamData4 = JSON.parseObject(value, TeamData.class);
                        TeamFriendZanHomeCTR.getInstance().setParms(teamData4.getData().getCanClickCount(), teamData4.getData().getMinWait(),
                                teamData4.getData().getMaxWait(), teamData4.getData().getCanClickCount(), teamData4.getData().getContent());
                        addType = Const.KEY_TEAM_RQ_FRIEND_ZANS;
                        NLogger.d(TAG, "开始执行任务 邀请好友点赞主页");
                        break;
                    default:
                        break;
                }
                AppContext.taskType = addType;
                PreferenceHelper.putInt(Const.PREF_KEY_ADD_PEOPLE_TYPE, addType);
                EventBus.getDefault().post(new Integer(addType));
                sendToServerFlag(AppContext.taskId, 1, "开始执行");

                AppUtil.jumpToFb(AppContext.getInstance().getContext());

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
